#pragma once

#include "server.hpp"


namespace commontcp {
    namespace server {
        // start mutiple servers in few threads
        class multiple_server
            : private boost::noncopyable
        {
        public:
            multiple_server()
            {

            }
            ~multiple_server()
            {                
                stop();
            }

            // start an server
            template<class t_session_handler>
            boost::shared_ptr< server<t_session_handler> >
                start_an_server(const std::string& address, const std::string& port, boost::shared_ptr<t_session_handler> thehandler)
            {
                return boost::shared_ptr< server<t_session_handler> >( new server<t_session_handler>(address, port, thehandler, io_service_) );
            }
            
            void async_start()
            {
                exitflag_ = false;
                // Create a pool of threads to run all of the io_services.                
                for (std::size_t i = 0; i < 4; ++i)
                {
                    boost::shared_ptr<boost::thread> thread(new boost::thread(
                        boost::bind(&multiple_server::run, this)));
                    threads.push_back(thread);
                }   
            }

            void stop()
            {
                io_service_.stop();
                exitflag_ = true;
                // Wait for all threads in the pool to exit.
                for (std::size_t i = 0; i < threads.size(); ++i)
                    threads[i]->join();
            }
        private:
            /// Run the server's io_service loop.
            void run()
            {   
                boost::system::error_code ec;
                while(!exitflag_)  
                {
                    io_service_.poll(ec);
                    boost::this_thread::sleep(boost::posix_time::milliseconds(10));
                }
            }
        private:
            boost::asio::io_service             io_service_;
            std::vector<boost::shared_ptr<boost::thread> > 
                                                threads;
            bool                                exitflag_;
        };
    }
}